#!/bin/bash
# This script is released under the GNU General Public License 3.0

# sample dialog handler for tzselect
# MUST have same input/output as the showdialog() function in tzselect

# showdialog()
# All normal user input/output goes through this function
#
# The user dialog of this script can be altered by setting
# the SHOWDIALOG variable as in:
# SHOWDIALOG=$PWD/tzselect_dialog tzselect
# where 'tzselect_dialog' imitates this function
#
# Arguments:
#  Type: one of: menu, yesno, msgbox, inputbox
#  Message: text to display
#  Options: menu-options, only for types menu and yesno

# location of other scripts to source
readonly SHAREDIR="$(dirname ${0})" || exit $?

# source common variables, functions and error handling
source "${SHAREDIR}"/common.sh || exit $?

# get type and message first
TYPE="${1}"
shift
MSG="${1}"
# hotfix message, do not print date/time
MSG="$(echo -n "${MSG}" | grep -v '[tT]ime is now:[[:blank:]]')" || exit $?
shift
MENU_ITEMS=(0 0)
RET_DIALOG=

case "${TYPE}" in
	# prepare arguments to dialog/Xdialog --menu
	menu)
		# add menu-height: auto
		MENU_ITEMS+=(0)
		# add value and description
		while [ $# -gt 0 ]; do
			MENU_ITEMS+=("$(( ( ${#MENU_ITEMS[@]} -1 ) / 2 ))" "${1}")
			shift
		done ;;
esac

# use dialog/Xdialog
ANSWER=$(show_dialog \
	--no-cancel \
	"--${TYPE}" \
	"${MSG}" \
	"${MENU_ITEMS[@]}")
RET_DIALOG=$?

# exit on cancel unless it's a yesno
[ "${TYPE}" != 'yesno' ] && [ "${RET_DIALOG}" -ne 0 ] && exit "${RET_DIALOG}"

case "${TYPE}" in
	yesno)
		if [ "${RET_DIALOG}" -eq 0 ]; then
			ANSWER=$([ -n "${1}" ] && echo -n "${1}" || echo -n Yes)
		else
			ANSWER=$([ -n "${2}" ] && echo -n "${2}" || echo -n No)
		fi ;;
	# get string from index
	menu)
		ANSWER="${MENU_ITEMS[(($ANSWER * 2 + 2))]}" || exit $? ;;
esac
# print result
echo -n "${ANSWER}"
exit 0
